#!/bin/bash
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
COMMON_SHELL="$SCRIPT_DIR/../common.sh" 
SFTP_TOOL="$SCRIPT_DIR/../tools/sftp"

if [ ! -f "$COMMON_SHELL" ]; then
    if [ ! -f ./common.sh ]; then
        wget https://gitee.com/anolis/hygon-devkit/raw/master/common.sh
        chmod +x common.sh
    fi
    source ./common.sh
else
    source $COMMON_SHELL
fi

PKG_SUFFIX=$(get_os_info | sed -n '1p')

# Check if the correct number of arguments is provided
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <version>"
    exit 1
fi

SEARCH_PATH=/hygon-devkit/4.0/2025-01-01/hpt/hpt-$1
# Get the file name at remote path
if [ ! -f "$SFTP_TOOL" ]; then
    if [ ! -f ./sftp ]; then
        wget https://gitee.com/anolis/hygon-devkit/raw/master/tools/sftp
    fi
    chmod +x sftp
    FILE_NAME=$(./sftp  list "$SEARCH_PATH" | grep -oP "hpt-\Q$1\E-.*?\.tar.gz$")
    if [ -z "$FILE_NAME" ]; then
        FILE_NAME=$(./sftp list "$SEARCH_PATH" |  grep -oP "hpt[-_]$1[-_][0-9]+[._][^.]+\.$PKG_SUFFIX$" | awk '{print $1}')
    fi
else
    FILE_NAME=$($SFTP_TOOL list "$SEARCH_PATH" | grep -oP "hpt-\Q$1\E-.*?\.tar.gz$")
    if [ -z "$FILE_NAME" ]; then
        FILE_NAME=$("$SFTP_TOOL" list "$SEARCH_PATH" |  grep -oP "hpt[-_]$1[-_][0-9]+[._][^.]+\.$PKG_SUFFIX$" | awk '{print $1}')
    fi
fi

if [ -z "$FILE_NAME" ]; then
    echo "FILE not found at sftp server"
    exit 1
fi

REMOTE_PATH=/hygon-devkit/4.0/2025-01-01/hpt/hpt-$1/$FILE_NAME
LOCAL_DIR=${SCRIPT_DIR}/pkg/hpt-$1

# Create the local directory if it doesn't exist
mkdir -p "$LOCAL_DIR"
echo "Downloading $REMOTE_PATH to $LOCAL_DIR/$FILE_NAME"

# If the directory don't have the file, download it
if [ -z "$(ls -A "$LOCAL_DIR"/$FILE_NAME 2>/dev/null)" ] ; then
    if [ ! -f "$SFTP_TOOL" ]; then
        ./sftp download "$REMOTE_PATH" $LOCAL_DIR/$FILE_NAME
    else
        $SFTP_TOOL download "$REMOTE_PATH" $LOCAL_DIR/$FILE_NAME
    fi
fi

echo "Installing $FILE_NAME"
if [[ "$FILE_NAME" == *.deb ]]; then
    dpkg -i $LOCAL_DIR/$FILE_NAME
elif [[ "$FILE_NAME" == *.rpm ]]; then
    rpm -ivh --replacefiles $LOCAL_DIR/$FILE_NAME
else
    echo "Extracting $LOCAL_DIR/$FILE_NAME to /opt/hygon"
    tar -zxvf $LOCAL_DIR/$FILE_NAME -C /opt/hygon
fi
